package org.kwin.ibatis.session;

import org.kwin.spring.jdbc.session.SqlSessionFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author : wangkai
 * @version V1.0
 * @Package org.kwin.ibatis.session
 * @Description:
 * @date 2021年10月09日 14:18
 **/
public class DefaultSqlSessionFactory implements SqlSessionFactory {
    
    private SqlConfig config;
    
    // 非事务的连接
    private Connection connection;
    
    public DefaultSqlSessionFactory(SqlConfig config) {
        this.config = config;
    }
    
    @Override
    public SqlSession openSession() {
        return new SqlSession(getConnection());
    }
    
    @Override
    public SqlSession openSession(boolean transaction) {
        return transaction ? new SqlSession(newConnection(), true) : openSession();
    }
    
    @Override
    public SqlConfig getConfiguration() {
        return null;
    }
    
    private Connection getConnection()
    {
        try
        {
            if (connection == null || connection.isClosed())
            {
                connection = DriverManager.getConnection(config.url, config.username, config.password);
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return connection;
    }
    
    private Connection newConnection()
    {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(config.url, config.username, config.password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    
        return connection;
    }
}
